package com.cloudbroker.bcs.platform.dav.middle.aspect;

import java.util.Date;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudbroker.bcs.csvc.uc.api.vo.request.base.UCForm;
import com.cloudbroker.bcs.csvc.uc.api.vo.response.UserInfoBackVo;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.hundsun.jres.common.util.UUID;

public class CompanyIdConversAspect {
    
    @Resource
    private TenantService tenantService;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyIdConversAspect.class);
    
    public Object conversTenantIdByCompanyId(ProceedingJoinPoint pjp) throws Throwable {
        Object arg = pjp.getArgs()[0];
        Integer tenId = null;
        if (arg instanceof UCForm) {
            UCForm param = (UCForm) arg;
            if (param.getTenant_id() != null) {
                tenId = param.getTenant_id();
                Integer company_id = tenantService.getCompanyIdByTenantId(tenId);
                param.setTenant_id(company_id);
            }
        }
        Object ret = pjp.proceed();
        if (ret instanceof UserInfoBackVo) {
            UserInfoBackVo back = (UserInfoBackVo) ret;
            if (tenId != null) {
                back.setTenant_id(tenId);
                return back;
            }
            Integer company_id = back.getTenant_id();
            Integer tenantId = SessionHelper.getInstance().getTenantIdByCompanyId(company_id);
            if (tenantId != null) {
                back.setTenant_id(tenantId);
                return back;
            }
            Tenant tenant = tenantService.getByCompanyId(company_id);
            if (tenant == null) {
                LOGGER.error("companyid：" + company_id + "租户未找到");
                tenant = new Tenant();
                tenant.setTenant_key(UUID.randomUUID().toString());
                tenant.setCreate_date(new Date());
                tenant.setCompany_id(String.valueOf(company_id));
                tenant.setName("租户" + company_id);
                tenantService.save(tenant);
                return back;
            }
            tenantId = tenant.getTenant_id();
            SessionHelper.getInstance().setTenantCompanyIdRel(tenantId, company_id);
            return back;
        }
        return ret;
    }
    
}
